package com.fone.player.play.fragment;

import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.activity.BaseFragment;
import com.fone.player.client.Callback;
import com.fone.player.client.CommentlistRst;
import com.fone.player.client.CommentlistRst.Comment;
import com.fone.player.client.Error;
import com.fone.player.client.Reporter;
import com.fone.player.client.Request;
import com.fone.player.client.Rst;
import com.fone.player.play.adapter.VideoCommentAdapter;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.view.ColorBallProgressView;
import com.fone.player.widget.xlistview.XListView;

/**
 * 视频评论
 * 
 * @author kongxiaojun
 * @since 2014-4-29
 */
@SuppressLint("ValidFragment")
public class VideoCommentFragment extends BaseFragment implements View.OnClickListener {
	private static final String TAG = "VideoCommentFragment";
	/** 内容view */
	private View contentView;
	/** 评论列表 */
	private XListView listView;
	/** 头部发表评论view */
	private View header;
	/** 发布评论url */
	private String commentUrl;
	/** 取评论列表接口 */
	private String commentListUrl;
	/** commment list adapter */
	private VideoCommentAdapter adapter;
	/** comment edittext */
	private EditText etComment;
	/** submit comment button */
	private Button submitComment;
	/** 评论数据bean */
	private CommentlistRst comRst;
	/** 评论列表 */
	private List<Comment> comments;
	/** 圆形进度条 */
	private ColorBallProgressView commentLoading;
	/** 是否正在提交评论 */
	private boolean commenting;

	public static final Fragment newInstances(String commentUrl, String commentListUrl) {
		Fragment fragment = new VideoCommentFragment();
		Bundle bundle = new Bundle();
		bundle.putString("commentUrl", commentUrl);
		bundle.putString("commentListUrl", commentListUrl);
		fragment.setArguments(bundle);
		return fragment;
	}

	public VideoCommentFragment() {
		super();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		contentView = inflater.inflate(R.layout.video_comment, null);

		this.commentUrl = FoneUtil.handleUrl(getArguments().getString("commentUrl"));
		this.commentListUrl = FoneUtil.handleUrl(getArguments().getString("commentListUrl"));

		listView = (XListView) contentView.findViewById(R.id.video_comment_list);
		commentLoading = (ColorBallProgressView) contentView.findViewById(R.id.comment_loading);
		listView.setXListViewListener(new XListView.IXListViewListener() {

			@Override
			public void onRefresh() {
				// 清除EditText 焦点
				etComment.clearFocus();
				// 刷新
				requestCommentList();
			}

			@Override
			public void onLoadMore() {
				// 清除EditText 焦点
				etComment.clearFocus();
				// 加载更多
				requestMoreCommentList();
			}
		});
		header = inflater.inflate(R.layout.video_comment_list_header, null);
		etComment = (EditText) header.findViewById(R.id.video_comment_et);
		submitComment = (Button) header.findViewById(R.id.video_comment_bt);
		submitComment.setOnClickListener(this);
		listView.addHeaderView(header);
		adapter = new VideoCommentAdapter();
		listView.setAdapter(adapter);
		etComment.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					if (!FoneUtil.isNetOkWithToast(getActivity())) {
						etComment.clearFocus();
					} else if (!UserInfoManager.isLogin()) {
						FoneUtil.toLoginPage(getActivity(), "7");
						etComment.clearFocus();
					}
				}
			}
		});
		if (FoneUtil.isNetOk(getActivity())) {
			commentLoading.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
			requestCommentList();
		}
		return contentView;
	}

	private void requestCommentList() {
		Request.getInstance().commentlist(commentListUrl, new Callback<CommentlistRst>() {

			@Override
			public void onSuccess(CommentlistRst t) {
				if (destory) {
					return;
				}
				commentLoading.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				listView.stopRefresh();
				listView.setRefreshTime(FoneUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
				if (t == null) {
					return;
				}
				if (t.result == 0) {
					comRst = t;
					comments = t.comments.commentList;
					adapter.setData(comments);
					if (TextUtils.isEmpty(t.rp.nurl) || t.comments.commentList == null || t.comments.commentList.size() == 0) {
						// 没有更多
						listView.setPullLoadEnable(false);
					} else {
						listView.setPullLoadEnable(true);
					}
				} else {
					// 出错了
					if (t.error != null && !TextUtils.isEmpty(t.error.errormsg) && getActivity() != null) {
						Toast.makeText(getActivity(), t.error.errormsg, Toast.LENGTH_SHORT).show();
					}
				}
			}

			@Override
			public void onFailure(Error error) {
				if (destory) {
					return;
				}
				commentLoading.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				listView.stopRefresh();
				// 提示
				L.v(TAG, "requestCommentList onFailure " + error.getReason());
				// if (error.isNetworkError() && getActivity() != null) {
				// Toast.makeText(getActivity(),
				// R.string.player_network_not_stable,
				// Toast.LENGTH_SHORT).show();
				// } else if (getActivity() != null) {
				// Toast.makeText(getActivity(), error.getReason(),
				// Toast.LENGTH_SHORT).show();
				// }
			}
		});
	}

	private void requestMoreCommentList() {
		Request.getInstance().commentlist(FoneUtil.handleUrl(comRst.rp.nurl), new Callback<CommentlistRst>() {

			@Override
			public void onSuccess(CommentlistRst t) {
				if (destory) {
					return;
				}
				listView.stopLoadMore();
				if (t == null) {
					return;
				}
				if (t.result == 0) {
					comRst = t;
					if (t.comments.commentList != null && t.comments.commentList.size() > 0) {
						comments.addAll(t.comments.commentList);
					}
					adapter.setData(comments);
					if (TextUtils.isEmpty(t.rp.nurl) || t.comments.commentList == null || t.comments.commentList.size() == 0) {
						// 没有更多
						listView.setPullLoadEnable(false);
					} else {
						listView.setPullLoadEnable(true);
					}
				} else {
					// 出错了
					if (t.error != null && !TextUtils.isEmpty(t.error.errormsg) && getActivity() != null) {
						Toast.makeText(getActivity(), t.error.errormsg, Toast.LENGTH_SHORT).show();
					}
				}
			}

			@Override
			public void onFailure(Error error) {
				if (destory) {
					return;
				}
				listView.stopLoadMore();
				// 提示
				L.v(TAG, "requestMoreCommentList onFailure " + error.getReason());
				// if (error.isNetworkError() && getActivity() != null) {
				// Toast.makeText(getActivity(),
				// R.string.player_network_not_stable,
				// Toast.LENGTH_SHORT).show();
				// } else if (getActivity() != null) {
				// Toast.makeText(getActivity(), error.getReason(),
				// Toast.LENGTH_SHORT).show();
				// }
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.video_comment_bt:// 提交评论
			new Thread(new Runnable() {
				@Override
				public void run() {
					Reporter.logEvent(Reporter.EventId.CLICK_DETAIL_BTN);
				}
			}).start();
			if (commenting) {
				return;
			}
			if (!FoneUtil.isNetOkWithToast(getActivity())) {
				return;
			}
			if (UserInfoManager.isLogin()) {
				if (TextUtils.isEmpty(etComment.getText().toString().trim())) {
					Toast.makeText(getActivity(), R.string.player_comment_text_null, Toast.LENGTH_SHORT).show();
				} else {
					submitComment();
				}
			} else {
				FoneUtil.toLoginPage(getActivity(), "7");
			}
			break;

		default:
			break;
		}
	}

	/**
	 * 提交评论
	 * 
	 * @return void
	 * @throws
	 */
	private void submitComment() {
		commenting = true;
		String content = FoneUtil.Base64Encode(etComment.getText().toString().getBytes());
		Request.getInstance().comment(commentUrl, content, new Callback<Rst>() {

			@Override
			public void onSuccess(Rst t) {
				if (destory) {
					return;
				}
				commenting = false;
				if (t == null) {
					return;
				}
				if (t.result == 0) {
					if (getActivity() != null) {
						Toast.makeText(getActivity(), R.string.player_comment_success, Toast.LENGTH_SHORT).show();
					}
					requestCommentList();
					etComment.setText("");
					FoneUtil.hideInputMethod(etComment, getActivity());
				} else {
					// 出错了
					// if (t.error != null &&
					// !TextUtils.isEmpty(t.error.errormsg) && getActivity() !=
					// null) {
					// Toast.makeText(getActivity(), t.error.errormsg,
					// Toast.LENGTH_SHORT).show();
					// }
				}
			}

			@Override
			public void onFailure(Error error) {
				if (destory) {
					return;
				}
				commenting = false;
				if (getActivity() != null) {
					L.v(TAG, "submitComment onFailure " + error.getReason());
					Toast.makeText(getActivity(), R.string.player_comment_failed, Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	@Override
	public void onDetach() {
		super.onDetach();
		L.v(TAG, "onDetach");
	}

	@Override
	public void onPause() {
		super.onPause();
		L.v(TAG, "onPause");
	}

	@Override
	public void onStop() {
		super.onStop();
		L.v(TAG, "onStop");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		L.v(TAG, "onDestroy");
		if (listView != null) {
			listView.removeAllViewsInLayout();
			listView = null;
		}
		commentLoading = null;
		contentView = null;
		adapter = null;
		header = null;
		etComment = null;
		submitComment = null;
		contentView = null;
		if (comments != null) {
			comments.clear();
		}
		comRst = null;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		FoneUtil.hideInputMethod(etComment, getActivity());
	}

	public void setCommentUrl(String commentUrl) {
		this.commentUrl = commentUrl;
	}

	public void setCommentListUrl(String commentListUrl) {
		this.commentListUrl = commentListUrl;
	}

}
